package com.traffic.between.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;


public class FuYanServiceImpl {
	private static Logger logger = Logger.getLogger(FuYanServiceImpl.class);
	public static FuYanServiceImpl service = new FuYanServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.FUYAN_ORDER_URL;
	private static String FUYAN_APPKEY = BetweenProperties.FUYAN_APPKEY;
	private static String FUYAN_USERNAME = BetweenProperties.FUYAN_USERNAME;
	private static String FUYAN_PASSWORD = BetweenProperties.FUYAN_PASSWORD;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.FUYAN_ORDERSTATUS_URL;
	
	

	public String order(String product, String phone, String orderId) {
	
        String username = FUYAN_USERNAME;
        String password = FUYAN_PASSWORD;
        String key = FUYAN_APPKEY;
        String type = "1";
       
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d = new Date();
		String timestamp = sdf.format(d);
		 String echostr = timestamp;
		
        String waitSig = username + password + echostr + orderId + timestamp + phone + type + product + key;
        String sign = getMD5(waitSig.trim());
        String result = "";
        
       
	
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("username", username));
        pairList.add(new BasicNameValuePair("password", password));
        pairList.add(new BasicNameValuePair("echostr", echostr));
        pairList.add(new BasicNameValuePair("orderid", orderId));
        pairList.add(new BasicNameValuePair("timestamp", timestamp));
        pairList.add(new BasicNameValuePair("phone", phone));
        pairList.add(new BasicNameValuePair("type", type));
        pairList.add(new BasicNameValuePair("product", product));
        pairList.add(new BasicNameValuePair("sign", sign));
       
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 福研流量订购请求时的参数: " + pairList);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 福研流量订购请求时的响应数据是: " + result+",该订单号："+orderId);
			}
			
		} catch (Exception e) {
			logger.info("between- 福研流量订购请求时的响应异常: " +e.getMessage());
			
		}

	
		return result;
	}

	
	
	
	
	
	
	public String orderStatus(String cstmOrderNo) {

		logger.info("between- 福研订购状态请求参数: params cstmOrderNo = " + cstmOrderNo);
		String username = FUYAN_USERNAME;
	    String password = FUYAN_PASSWORD;
	    String waitSign = username+password+cstmOrderNo+FUYAN_APPKEY;
	    String sign = getMD5(waitSign).trim();//md5加密
	    String result = "";
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("username", username));
        pairList.add(new BasicNameValuePair("password", password));
        pairList.add(new BasicNameValuePair("orderid", cstmOrderNo));
        pairList.add(new BasicNameValuePair("sign", sign));
        
    	HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 福研流量订购请求时的响应数据是: " + result);
			}
		} catch (Exception e) {
			logger.info("between- 福研流量查询请求时的响应异常: " +e.getMessage());
		    Map<String, String> map = new HashMap<String, String>();
		    map.put("code","000000");
		    map.put("msg", e.getMessage());
		    result = new Gson().toJson(map);
		}
		return result;
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}



}
